package com.ymatou.iapi.sellercs.testcase;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.http.client.ClientProtocolException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.google.gson.JsonObject;
import com.ymatou.iapi.sellercs.parameter.CsSessionDetail;
import com.ymatou.iapi.sellercs.parameter.SellerSendMessageBean;
import com.ymatou.iapi.sellercs.parameter.SendMessageBean;
import com.ymatou.iapi.sellercs.parameter.TransferSessionBean;
import com.ymatou.iapi.sellercs.service.TransferSessionCall;
import com.ymatou.iapi.userregister.parameter.UserRegisterInfoRequestDtoBean;
import com.ymatou.iapi.userregister.service.UserRegisterInfoRequestDtoCall;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.*;
import com.ymt.utils.tag.*;
import com.ymttest.business.service.JUserCallService;
import com.ymttest.business.service.SellerCSIMCallService;
import com.ymttest.database.model.YmtCssession;
import com.ymttest.database.model.YmtQueuesession;
import com.ymttest.database.redis.ImRedisWapper;
import com.ymttest.database.sqlwapper.YmtSellerCSIMWapper;
import com.ymttest.utils.EnvSetup;

import redis.clients.jedis.Tuple;

/**
 * 会话转接 FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_TransferSession {
	private static TransferSessionBean transfersessionBean;
	private static TransferSessionCall transfersessionCall;
	private static int sellerId = Integer.parseInt(EnvSetup.getData("autotest_seller1"));
	private static String sellername = EnvSetup.getData("autotest_sellerName1");
	private static YmtSellerCSIMWapper YmtSellerCSIMWapper;
	private static int zsellerId = Integer.parseInt(EnvSetup.getData("autotest_seller_z"));

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("会话转接");
	}

	@Before
	public void caseUp() throws ClientProtocolException, IOException {
		transfersessionBean = new TransferSessionBean();
		transfersessionCall = new TransferSessionCall();
		YmtSellerCSIMWapper = new YmtSellerCSIMWapper();
		SellerCSIMCallService.OffLine(sellerId, null);
		SellerCSIMCallService.OffLine(zsellerId, null);
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(transfersessionCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	/**
	 * 验证会话状态
	 * 
	 * @param SendMessageBean
	 * @param unReadCount
	 * @throws InterruptedException
	 */
	private void verifyDB(SendMessageBean SendMessageBean, Integer unReadCount, Integer tsellerid) throws InterruptedException {
		List<YmtCssession> infos = YmtSellerCSIMWapper.selectYmtCssession(SendMessageBean.getCSId(), SendMessageBean.getFromUserId());
		Logger.comment("验证首次接入方");
		YmtCssession finfo = infos.stream().filter(info -> {
			return info.getCSId().equals(SendMessageBean.getCSId());
		}).collect(Collectors.toList()).get(0);
		Logger.debug("YmtQueuesession:" + FormatUtil.beanToGSONString(finfo));
		Logger.verifyNotNull(finfo.getBeginTime(), "验证BeginTime");
		Logger.verifyEquals(13, finfo.getFromPlatform(), "来源平台-固定13");
		Logger.verifyEquals(true, new Date().getTime() - finfo.getLastMessageTime().getTime() < 10000, "LastMessageTime-误差内");
		Logger.verifyEquals(SendMessageBean.getCSId(), finfo.getMasterCSId(), "验证MasterCSId");
		Logger.verifyNotNull(finfo.getSessionNumber(), "验证SessionNumber");
		Logger.verifyEquals(unReadCount, finfo.getUnReadCount(), "unReadCount");
		// 0 User, 1 ReAssign, 2 CS
		Logger.verifyEquals(2, finfo.getOpenType(), "OpenType-2分配打开会话");
		Logger.verifyEquals(5, finfo.getCloseType(), "CloseType5转接");
		Logger.verifyEquals(1, finfo.getStatus(), "Status-1关闭");
		Logger.verifyEquals(0, finfo.getMark(), "Mark-0");

		Logger.comment("验证首次接入方");
		YmtCssession tinfo = infos.stream().filter(info -> {
			return info.getCSId().equals(tsellerid);
		}).collect(Collectors.toList()).get(0);
		Logger.debug("YmtQueuesession:" + FormatUtil.beanToGSONString(tinfo));
		Logger.verifyNotNull(tinfo.getBeginTime(), "验证BeginTime");
		Logger.verifyEquals(13, tinfo.getFromPlatform(), "来源平台-固定13");
		Logger.verifyEquals(true, new Date().getTime() - tinfo.getLastMessageTime().getTime() < 10000, "LastMessageTime-误差内");
		Logger.verifyEquals(SendMessageBean.getCSId(), tinfo.getMasterCSId(), "验证MasterCSId");
		Logger.verifyNotNull(tinfo.getSessionNumber(), "验证SessionNumber");
		Logger.verifyEquals(0, tinfo.getUnReadCount(), "unReadCount");
		// 0 User, 1 ReAssign, 2 CS
		Logger.verifyEquals(1, tinfo.getOpenType(), "OpenType-1ReAssign");
		Logger.verifyEquals(null, tinfo.getCloseType(), "CloseType未关闭null");
		Logger.verifyEquals(0, tinfo.getStatus(), "Status-0开启");
		Logger.verifyEquals(0, tinfo.getMark(), "Mark-0");
	}

	private void verifyRedis(SendMessageBean SendMessageBean, Integer unReadCount, Integer tsellerid) throws InterruptedException, ClientProtocolException, IOException {
		ImRedisWapper ImRedisWapper = new ImRedisWapper();
		Set<Tuple> set = ImRedisWapper.getCSession(sellerId);
		set.forEach(t -> {
			Logger.debug("tuple:" + t.getScore() + ":" + t.getElement());
		});
		List<String> list = set.stream().filter(t->{return Double.valueOf(sellerId).equals(t.getScore());}).map(t -> {
			return t.getElement();
		}).collect(Collectors.toList());
		Logger.verifyEquals(false, list.contains(SendMessageBean.getFromUserId().toString()), "验证CSession中包含有FromUserId");
		CsSessionDetail csSessionDetail = ImRedisWapper.getCSessionDetails(SendMessageBean.getCSId(), SendMessageBean.getFromUserId(),sellerId);
		Logger.debug("CSessionDetails:" + FormatUtil.beanToGSONString(csSessionDetail));
		Logger.verifyEquals(null, csSessionDetail, "验证原会话清除");

		set = ImRedisWapper.getCSession(sellerId);
		set.forEach(t -> {
			Logger.debug("tuple:" + t.getScore() + ":" + t.getElement());
		});
		list = set.stream().filter(t->{return Double.valueOf(tsellerid).equals(t.getScore());}).map(t -> {
			return t.getElement();
		}).collect(Collectors.toList());
		Logger.verifyEquals(true, list.contains(SendMessageBean.getFromUserId().toString()), "验证CSession中包含有FromUserId");
		csSessionDetail = ImRedisWapper.getCSessionDetails(tsellerid, SendMessageBean.getFromUserId(),tsellerid);
		Logger.debug("CSessionDetails:" + FormatUtil.beanToGSONString(csSessionDetail));

		Logger.verifyEquals(tsellerid, csSessionDetail.getCsId(), "验证csid");
		Logger.verifyEquals(JUserCallService.GetUserInfo(tsellerid).getLoginId(), csSessionDetail.getCsName(), "验证csname");
		Logger.verifyNotNull(csSessionDetail.getSessionId(), "验证SessionId不为空");
		Logger.verifyNotNull(csSessionDetail.getSessionNumber(), "验证SessionNumber不为空");

	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_TransferSession_001() {
		Logger.start(true, "会话转接,成功");
		try {
			Logger.comment("注册新用户");
			UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
			UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);

			JsonObject registerResult = urrc.getJsonObject().get("Result").getAsJsonObject();
			String token = registerResult.get("Token").getAsString();
			Integer userId = urrc.getUserid();
			Logger.comment("删除旧数据");
			YmtSellerCSIMWapper.deleteYmtOnlinecsByCsid(sellerId);
			// APP上线
			SellerCSIMCallService.AppLogin(sellerId);
			SendMessageBean sendmessageBean = SellerCSIMCallService.initSendmessageBean(userId, sellerId, "connect");
			SellerCSIMCallService.SendMessage(sendmessageBean);
			// 触发分配
			SellerCSIMCallService.Assign();
			Thread.sleep(3000);
			SellerCSIMCallService.AppLogin(zsellerId);
			transfersessionBean.setFromCSId(sellerId);
			transfersessionBean.setToCSId(zsellerId);
			transfersessionBean.setUserId(userId);
			transfersessionCall.setData(transfersessionBean);
			transfersessionCall.callService();
			Logger.verifyIsContains("200", transfersessionCall.getString("Status"), "验证Status");
			Logger.verifyEquals(true, transfersessionCall.getJsonObject().get("Result").getAsJsonObject().get("IsSuccess").getAsBoolean(), "验证IsSuccess");
			Thread.sleep(1000);
			verifyDB(sendmessageBean, 1, zsellerId);
			verifyRedis(sendmessageBean, 1, zsellerId);
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P2.class })
	@TestCase
	public void Tc_TransferSession_002() {
		Logger.start(true, "已结束会话转接失败");
		try {
			Logger.comment("注册新用户");
			UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
			UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);

			JsonObject registerResult = urrc.getJsonObject().get("Result").getAsJsonObject();
			String token = registerResult.get("Token").getAsString();
			Integer userId = urrc.getUserid();
			Logger.comment("删除旧数据");
			YmtSellerCSIMWapper.deleteYmtOnlinecsByCsid(sellerId);
			// APP上线
			SellerCSIMCallService.AppLogin(sellerId);
			SendMessageBean sendmessageBean = SellerCSIMCallService.initSendmessageBean(userId, sellerId, "connect");
			SellerCSIMCallService.SendMessage(sendmessageBean);
			// 触发分配
			SellerCSIMCallService.Assign();
			Thread.sleep(3000);
			SellerCSIMCallService.OffLine(sellerId, null);
			SellerCSIMCallService.AppLogin(zsellerId);
			transfersessionBean.setFromCSId(sellerId);
			transfersessionBean.setToCSId(zsellerId);
			transfersessionBean.setUserId(userId);
			transfersessionCall.setData(transfersessionBean);
			transfersessionCall.callService();
			Logger.verifyIsContains("200", transfersessionCall.getString("Status"), "验证Status");
			Logger.verifyEquals(false, transfersessionCall.getJsonObject().get("Result").getAsJsonObject().get("IsSuccess").getAsBoolean(), "验证IsSuccess");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P3.class })
	@TestCase
	public void Tc_TransferSession_003() {
		Logger.start(true, "不输入FromCSId失败");
		try {
			Logger.comment("注册新用户");
			UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
			UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);

			JsonObject registerResult = urrc.getJsonObject().get("Result").getAsJsonObject();
			String token = registerResult.get("Token").getAsString();
			Integer userId = urrc.getUserid();
//			Logger.comment("删除旧数据");
//			YmtSellerCSIMWapper.deleteYmtOnlinecsByCsid(sellerId);
//			// APP上线
//			SellerCSIMCallService.AppLogin(sellerId);
//			SendMessageBean sendmessageBean = SellerCSIMCallService.initSendmessageBean(userId, sellerId, "connect");
//			SellerCSIMCallService.SendMessage(sendmessageBean);
//			// 触发分配
//			SellerCSIMCallService.Assign();
//			Thread.sleep(5000);
//			SellerCSIMCallService.OffLine(sellerId, null);
//			SellerCSIMCallService.AppLogin(zsellerId);
//			transfersessionBean.setFromCSId(sellerId);
			transfersessionBean.setToCSId(zsellerId);
			transfersessionBean.setUserId(userId);
			transfersessionCall.setData(transfersessionBean);
			transfersessionCall.callService();
			Logger.verifyIsContains("400", transfersessionCall.getString("Status"), "验证Status");
//			Logger.verifyEquals(true, transfersessionCall.getJsonObject().get("Result").getAsJsonObject().get("IsSuccess").getAsBoolean(), "验证IsSuccess");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P3.class })
	@TestCase
	public void Tc_TransferSession_004() {
		Logger.start(true, "不输入ToCSId失败");
		try {
			Logger.comment("注册新用户");
			UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
			UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);

			JsonObject registerResult = urrc.getJsonObject().get("Result").getAsJsonObject();
			String token = registerResult.get("Token").getAsString();
			Integer userId = urrc.getUserid();
//			Logger.comment("删除旧数据");
//			YmtSellerCSIMWapper.deleteYmtOnlinecsByCsid(sellerId);
//			// APP上线
//			SellerCSIMCallService.AppLogin(sellerId);
//			SendMessageBean sendmessageBean = SellerCSIMCallService.initSendmessageBean(userId, sellerId, "connect");
//			SellerCSIMCallService.SendMessage(sendmessageBean);
//			// 触发分配
//			SellerCSIMCallService.Assign();
//			Thread.sleep(5000);
//			SellerCSIMCallService.OffLine(sellerId, null);
//			SellerCSIMCallService.AppLogin(zsellerId);
			transfersessionBean.setFromCSId(sellerId);
//			transfersessionBean.setToCSId(zsellerId);
			transfersessionBean.setUserId(userId);
			transfersessionCall.setData(transfersessionBean);
			transfersessionCall.callService();
			Logger.verifyIsContains("400", transfersessionCall.getString("Status"), "验证Status");
//			Logger.verifyEquals(true, transfersessionCall.getJsonObject().get("Result").getAsJsonObject().get("IsSuccess").getAsBoolean(), "验证IsSuccess");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P3.class })
	@TestCase
	public void Tc_TransferSession_005() {
		Logger.start(true, "不输入UserId失败");
		try {
			Logger.comment("注册新用户");
			UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
			UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);

			JsonObject registerResult = urrc.getJsonObject().get("Result").getAsJsonObject();
			String token = registerResult.get("Token").getAsString();
			Integer userId = urrc.getUserid();
//			Logger.comment("删除旧数据");
//			YmtSellerCSIMWapper.deleteYmtOnlinecsByCsid(sellerId);
//			// APP上线
//			SellerCSIMCallService.AppLogin(sellerId);
//			SendMessageBean sendmessageBean = SellerCSIMCallService.initSendmessageBean(userId, sellerId, "connect");
//			SellerCSIMCallService.SendMessage(sendmessageBean);
//			// 触发分配
//			SellerCSIMCallService.Assign();
//			Thread.sleep(5000);
//			SellerCSIMCallService.OffLine(sellerId, null);
//			SellerCSIMCallService.AppLogin(zsellerId);
			transfersessionBean.setFromCSId(sellerId);
			transfersessionBean.setToCSId(zsellerId);
//			transfersessionBean.setUserId(userId);
			transfersessionCall.setData(transfersessionBean);
			transfersessionCall.callService();
			Logger.verifyIsContains("400", transfersessionCall.getString("Status"), "验证Status");
//			Logger.verifyEquals(true, transfersessionCall.getJsonObject().get("Result").getAsJsonObject().get("IsSuccess").getAsBoolean(), "验证IsSuccess");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P2.class })
	@TestCase
	public void Tc_TransferSession_006() {
		Logger.start(true, "UserId不存在失败");
		try {
//			Logger.comment("注册新用户");
//			UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
//			UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);
//
//			JsonObject registerResult = urrc.getJsonObject().get("Result").getAsJsonObject();
//			String token = registerResult.get("Token").getAsString();
//			Integer userId = urrc.getUserid();
//			Logger.comment("删除旧数据");
//			YmtSellerCSIMWapper.deleteYmtOnlinecsByCsid(sellerId);
//			// APP上线
//			SellerCSIMCallService.AppLogin(sellerId);
//			SendMessageBean sendmessageBean = SellerCSIMCallService.initSendmessageBean(userId, sellerId, "connect");
//			SellerCSIMCallService.SendMessage(sendmessageBean);
//			// 触发分配
//			SellerCSIMCallService.Assign();
//			Thread.sleep(5000);
//			SellerCSIMCallService.OffLine(sellerId, null);
//			SellerCSIMCallService.AppLogin(zsellerId);
//			transfersessionBean.setFromCSId(sellerId);
			transfersessionBean.setToCSId(zsellerId);
			transfersessionBean.setUserId(-99999);
			transfersessionCall.setData(transfersessionBean);
			transfersessionCall.callService();
			Logger.verifyIsContains("400", transfersessionCall.getString("Status"), "验证Status");
//			Logger.verifyEquals(true, transfersessionCall.getJsonObject().get("Result").getAsJsonObject().get("IsSuccess").getAsBoolean(), "验证IsSuccess");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P2.class })
	@TestCase
	public void Tc_TransferSession_007() {
		Logger.start(true, "转接给自己失败");
		try {
			Logger.comment("注册新用户");
			UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
			UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);

			JsonObject registerResult = urrc.getJsonObject().get("Result").getAsJsonObject();
			String token = registerResult.get("Token").getAsString();
			Integer userId = urrc.getUserid();
			Logger.comment("删除旧数据");
			YmtSellerCSIMWapper.deleteYmtOnlinecsByCsid(sellerId);
			// APP上线
			SellerCSIMCallService.AppLogin(sellerId);
			SendMessageBean sendmessageBean = SellerCSIMCallService.initSendmessageBean(userId, sellerId, "connect");
			SellerCSIMCallService.SendMessage(sendmessageBean);
			// 触发分配
			SellerCSIMCallService.Assign();
			Thread.sleep(3000);
			SellerCSIMCallService.AppLogin(zsellerId);
			transfersessionBean.setFromCSId(sellerId);
			transfersessionBean.setToCSId(sellerId);
			transfersessionBean.setUserId(userId);
			transfersessionCall.setData(transfersessionBean);
			transfersessionCall.callService();
			Logger.verifyIsContains("200", transfersessionCall.getString("Status"), "验证Status");
			Logger.verifyEquals(false, transfersessionCall.getJsonObject().get("Result").getAsJsonObject().get("IsSuccess").getAsBoolean(), "验证IsSuccess");
//{"Status":200,"Msg":"","Result":{"IsSuccess":false,"Tip":"不可转接给自己。"}}
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P2.class })
	@TestCase
	public void Tc_TransferSession_008() {
		Logger.start(true, "转接客服不在线失败");
		try {
			Logger.comment("注册新用户");
			UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
			UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);

			JsonObject registerResult = urrc.getJsonObject().get("Result").getAsJsonObject();
			String token = registerResult.get("Token").getAsString();
			Integer userId = urrc.getUserid();
			Logger.comment("删除旧数据");
			YmtSellerCSIMWapper.deleteYmtOnlinecsByCsid(sellerId);
			// APP上线
			SellerCSIMCallService.AppLogin(sellerId);
			SendMessageBean sendmessageBean = SellerCSIMCallService.initSendmessageBean(userId, sellerId, "connect");
			SellerCSIMCallService.SendMessage(sendmessageBean);
			// 触发分配
			SellerCSIMCallService.Assign();
			Thread.sleep(3000);
//			SellerCSIMCallService.AppLogin(zsellerId);
			transfersessionBean.setFromCSId(sellerId);
			transfersessionBean.setToCSId(zsellerId);
			transfersessionBean.setUserId(userId);
			transfersessionCall.setData(transfersessionBean);
			transfersessionCall.callService();
			Logger.verifyIsContains("200", transfersessionCall.getString("Status"), "验证Status");
			Logger.verifyEquals(false, transfersessionCall.getJsonObject().get("Result").getAsJsonObject().get("IsSuccess").getAsBoolean(), "验证IsSuccess");


		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P2.class })
	@TestCase
	public void Tc_TransferSession_009() {
		Logger.start(true, "转接给其他买手的客服失败");
		try {
			Logger.comment("注册新用户");
			UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
			UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);

			JsonObject registerResult = urrc.getJsonObject().get("Result").getAsJsonObject();
			String token = registerResult.get("Token").getAsString();
			Integer userId = urrc.getUserid();
			Logger.comment("删除旧数据");
			YmtSellerCSIMWapper.deleteYmtOnlinecsByCsid(sellerId);
			// APP上线
			SellerCSIMCallService.AppLogin(sellerId);
			SendMessageBean sendmessageBean = SellerCSIMCallService.initSendmessageBean(userId, sellerId, "connect");
			SellerCSIMCallService.SendMessage(sendmessageBean);
			// 触发分配
			SellerCSIMCallService.Assign();
			Thread.sleep(3000);
//			SellerCSIMCallService.AppLogin(zsellerId);
			transfersessionBean.setFromCSId(sellerId);
			transfersessionBean.setToCSId(3383);
			transfersessionBean.setUserId(userId);
			transfersessionCall.setData(transfersessionBean);
			transfersessionCall.callService();
			Logger.verifyIsContains("200", transfersessionCall.getString("Status"), "验证Status");
			Logger.verifyEquals(false, transfersessionCall.getJsonObject().get("Result").getAsJsonObject().get("IsSuccess").getAsBoolean(), "验证IsSuccess");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}